const _ = require("lodash");
const { defineConfig } = require("@vue/cli-service");
const { ModuleFederationPlugin } = require("webpack").container;
let {
  name,
  devDependencies,
  dependencies,
  peerDependencies,
  nipBundle,
} = require("./package.json");

const bundleDependencies = {
  ...devDependencies,
  ...dependencies,
  ...peerDependencies,
};
const bundleName = name.replace(/[@/-]/g, "_");
const toMap = (arr) => {
  let r = {};
  arr.forEach((a) => (r = _.merge(r, a)));
  return r;
};

module.exports = defineConfig({
  publicPath: "auto",
  runtimeCompiler: true,
  devServer: {
    port: 10203,
    allowedHosts: "all",
    headers: {
      "Access-Control-Allow-Origin": "*",
    },
  },

  css: {
    loaderOptions: {
      less: {
        lessOptions: {
          javascriptEnabled: true,
        },
      },
    },
  },
  configureWebpack: {
    optimization: {
      splitChunks: false,
    },
    plugins: [
      new ModuleFederationPlugin({
        name: bundleName,
        library: { type: "var", name: bundleName },
        filename: "bundle.js",
        exposes: {
          BundleInfo: _.get(nipBundle, "bundleInfo"),
          ...toMap(
            _.get(nipBundle, "modules", []).map((m) => {
              return {
                [m.id]: m.entry,
              };
            })
          ),
        },
        shared: {
          ...toMap(
            _.get(nipBundle, "shared", []).map((s) => {
              return {
                [s]: {
                  requiredVersion: bundleDependencies[s],
                  shareKey: s,
                  shareScope: "default",
                  singleton: true,
                },
              };
            })
          ),
        },
      }),
    ],
    resolve: {
      alias: {},
    },
  },
  chainWebpack: (config) => {
    const less = config.module.rule("less").toConfig();
    const lazy = { ...less.oneOf[3], test: /\.lazy\.less$/ };
    lazy.use = [...lazy.use];
    lazy.use[0] = {
      loader: "style-loader",
      options: {
        injectType: "lazyStyleTag",
        insert: function insertIntoTarget(element, options) {
          // style.use(options) will pass options here
          var parent = options.target || document.head;
          parent.appendChild(element);
        },
      },
    };
    config.module.rule("less").merge({ oneOf: [lazy] });
  },
});
